<template>
  <el-container class="layout-container">
    <el-aside width="200px">
      <div class="aside-first">
        <el-image :src="logoUrl" :fit="'scale-down'" />
      </div>

      <el-menu
          active-text-color="#ffd04b"
          background-color="#232323"
          text-color="#fff"
          :default-active="$route.path"
          router>
        <el-sub-menu index="admin-users">
          <template #title>
            <el-icon>
              <User />
            </el-icon>
            <span>用户管理</span>
          </template>
          <el-menu-item index="/admin/users">
            <el-icon>
              <User />
            </el-icon>
            <span>用户列表</span>
          </el-menu-item>
        </el-sub-menu>
           <!-- 新增：时间管理菜单 -->
        <el-sub-menu index="admin-time">
          <template #title>
            <el-icon>
              <Clock /> <!-- 需引入Clock图标 -->
            </el-icon>
            <span>时间管理</span>
          </template>
          <el-menu-item index="/admin/time">
            <el-icon>
              <Clock />
            </el-icon>
            <span>学习记录</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <strong>{{ userInfoStore.info.username }}</strong>
          </div>
          <div class="header-center">
            <dark-mode-slider></dark-mode-slider>
          </div>
          <div class="header-right">
            <el-dropdown placement="bottom-end" @command="handleCommand">
              <span class="el-dropdown__box">
                <el-avatar
                    :src="userInfoStore.info.avatarUrl ? userInfoStore.info.avatarUrl : 'https://img2.baidu.com/it/u=3926734404,2114692953&fm=253&fmt=auto&app=138&f=JPEG?w=807&h=800'" />
                <el-icon><CaretBottom /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      <el-main class="el-main">
        <el-card class="content-card" :body-style="{ padding: '20px' }">
          <div class="card-header">
            <h2 class="card-title">用户管理</h2>
            <div class="card-actions">
              <el-button type="primary" icon="el-icon-refresh" @click="getUserInfo">刷新</el-button>
            </div>
          </div>
          
          <div class="user-table-container">
            <el-table 
              :data="users" 
              style="width: 100%"
              stripe
              border
              :header-cell-style="{ background: '#f5f7fa', color: '#303133', fontWeight: '600' }"
              :row-class-name="tableRowClassName">
              <el-table-column prop="userId" label="ID" width="80" align="center" />
              <el-table-column label="用户信息" width="220">
                <template #default="scope">
                  <div class="user-info">
                    <el-avatar size="small" :src="scope.row.avatarUrl || 'https://picsum.photos/200/200'"></el-avatar>
                    <div class="user-details">
                      <div class="user-name">{{ scope.row.name || '未命名' }}</div>
                      <div class="user-phone">{{ scope.row.phone || '未设置' }}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="手机号" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column label="创建时间" prop="createTime" width="180" />
              <!-- <el-table-column label="更新时间" prop="updateTime" width="180" /> -->
              <el-table-column label="操作" width="180" align="center">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button 
                      size="small" 
                      type="primary" 
                      plain
                      @click="handleEdit(scope.row)">
                      <i class="el-icon-edit"></i> 编辑
                    </el-button>
                    <el-button 
                      size="small" 
                      type="danger" 
                      plain
                      @click="handleDelete(scope.row.userId)">
                      <i class="el-icon-delete"></i> 删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <el-pagination
            v-if="users.length > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-card>
      </el-main>
      <el-footer>基于Deepseek的408考研小助手</el-footer>
    </el-container>
    <small-window></small-window>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useTokenStore } from '@/stores/token.js';
import { useRouter } from 'vue-router';
import { CaretBottom, User, SwitchButton } from '@element-plus/icons-vue';
import DarkModeSlider from '@/components/DarkModeSlider.vue';
import SmallWindow from '@/components/SmallWindow.vue';
import { useThemeStore } from '@/stores/theme.js';
import useUserInfoStore from '@/stores/userInfo.js';

const router = useRouter();
const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();
const themeStore = useThemeStore();
const logoUrl = computed(() => themeStore.logoUrl);
const users = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取用户信息
const getUserInfo = async () => {
  try {
    const response = await axios.get('http://localhost:8080/user/selectAll', {
      headers: {
        'Authorization': `Bearer ${tokenStore.token}`,
      },
    });
    if (response.data && response.data.code === 0 && response.data.data) {
      users.value = response.data.data;
      total.value = response.data.data.length; // 假设返回的是全部数据
    } else {
      ElMessage.error('获取用户列表失败：' + (response.data.message || '未知错误'));
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败');
    console.error('Error fetching users:', error);
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('您确认要退出吗?', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
        .then(() => {
          tokenStore.removeToken();
          userInfoStore.removeInfo();
          localStorage.removeItem('role');
          router.push('/login');
          ElMessage.success('退出登录成功');
        })
        .catch(() => {
          ElMessage.info('用户取消了退出登录');
        });
  } else {
    router.push(command);
  }
};

// 编辑用户
const handleEdit = async (user) => {
  try {
    // 确保 userId 是一个有效的数字类型
    if (!user.userId || typeof user.userId !== 'number') {
      ElMessage.error('用户ID无效');
      return;
    }

    // 提示用户输入新的用户名
    const { value: name } = await ElMessageBox.prompt('请输入新的用户名', '编辑用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,20}$/,
      inputErrorMessage: '用户名格式不正确',
      inputValue: user.name, // 默认值为当前用户名
    });

    if (!name) return; // 如果用户取消操作，直接返回

    // 提示用户输入新的手机号
    const { value: phone } = await ElMessageBox.prompt('请输入新的手机号', '编辑用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^1[3-9]\d{9}$/,
      inputErrorMessage: '手机号格式不正确',
      inputValue: user.phone, // 默认值为当前手机号
    });

    if (!phone) return; // 如果用户取消操作，直接返回

    // 封装用户信息
    const updatedUser = {
      userId: user.userId, // 使用 userId 来定位用户
      name,
      phone,
    };

    // 调用后端接口更新用户信息
    const updateResponse = await axios.post('http://localhost:8080/user/update', updatedUser, {
      headers: {
        'Authorization': `Bearer ${tokenStore.token}`,
      },
    });

    if (updateResponse.data.code === 0) {
      ElMessage.success('用户信息更新成功');
      getUserInfo(); // 刷新用户列表
    } else {
      ElMessage.error('用户信息更新失败：' + updateResponse.data.message);
    }
  } catch (error) {
    if (error.response && error.response.data) {
      ElMessage.error('用户信息更新失败：' + error.response.data.message);
    } else {
      ElMessage.error('用户信息更新失败');
    }
    console.error('Error updating user:', error);
  }
};

// 删除用户
const handleDelete = async (userId) => {
  try {
    // 确保 userId 是一个有效的数字类型
    if (!userId || typeof userId !== 'number') {
      ElMessage.error('用户ID无效');
      return;
    }

    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const deleteResponse = await axios.get(`http://localhost:8080/user/delete?userId=${userId}`, {
      headers: {
        'Authorization': `Bearer ${tokenStore.token}`,
      },
    });

    if (deleteResponse.data.code === 0) {
      ElMessage.success('用户删除成功');
      getUserInfo(); // 刷新用户列表
    } else {
      ElMessage.error('用户删除失败：' + deleteResponse.data.message);
    }
  } catch (error) {
    if (error.response && error.response.data) {
      ElMessage.error('用户删除失败：' + error.response.data.message);
    } else {
      ElMessage.error('用户删除失败');
    }
    console.error('Error deleting user:', error);
  }
};

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return 'row-even';
  }
  return '';
};

onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.el-aside {
  background-color: #232323;
}

.aside-first {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
}

.el-menu {
  border-right: none;
  background-color: #232323;
  color: #fff;
}

.el-header {
  background-color: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.header-content {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
}

.header-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-content > * {
  margin: 0 10px;
}

.el-main {
  background-color: #f5f7fa;
  padding: 20px;
}

.el-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
  height: 40px;
}

.content-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.content-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.user-table-container {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
  color: #303133;
}

.user-phone {
  font-size: 12px;
  color: #606266;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.el-button {
  transition: all 0.2s ease;
}

.el-button:hover {
  transform: translateY(-1px);
}

.el-table__row.row-even {
  background-color: #fafafa;
}

.el-table__row:hover {
  background-color: #f5f7fa !important;
}

.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>